package student;

import jdbc.DBUtil;

import java.sql.*;
import java.util.List;

public class StudentDAOImpl implements Stu {
    @Override
    public int newly(Student student) {
        int row = 0;
        try (Connection conn = StudentUtil.getConnection()) {
            String sql = "insert into student(name,age,score) " +
                    "values('" + student.getName() + "'," + student.getAge() + "," + student.getScore() + ")";

            Statement statement = conn.createStatement();
            row = statement.executeUpdate(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return row;
    }

    @Override
    public int delete(int id) {
        int num = 0;
        try (Connection conn = StudentUtil.getConnection()) {
            String sql = "delete from student " +
                    "where id=" + id + " ";
            System.out.println(sql);
            Statement statement = conn.createStatement();
            num = statement.executeUpdate(sql);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public int change(Student student) {
        int num = 0;
        try (Connection conn = StudentUtil.getConnection()) {
            String sql = "update  student " +
                    "set name=?,age=?,score=? ";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, student.getName());
            ps.setInt(2, student.getAge());
            ps.setDouble(3, student.getScore());
            num = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }

    @Override
    public List<Student> selectAll() {
        try (Connection connection = DBUtil.getconnection()) {
            Statement statement = connection.createStatement();
            String sql = "SELECT id,name,age,score " +
                    "FROM student";
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                double score = rs.getDouble("score");
                System.out.println(id + "\t " + name + "\t " + age + "\t " + score);
            }
        } catch (SQLException e) {
            e.printStackTrace();

        }
        return null;
    }

    @Override
        public Student selectById(int id) {
        try( Connection conn = StudentUtil.getConnection()) {
            String sql="select id,name,age,score  " +
                    "from student " +
                    "where id=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setInt(1,id);

            ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
